/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Classes;

import AuxClasses.AddTransaccion;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Marvin
 */
public class Prestamo extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession actual = request.getSession();
        String dpi = actual.getAttribute("dpi").toString();
        String monto = request.getParameter("monto");
        Connection conn = null;
        Statement s = null;
        ResultSet rs = null;
        String userName = "root";
        String password = "1234";
        String url = "jdbc:mysql://localhost/bancofarmville";
        String error = "";
        
        Pattern p_monto = Pattern.compile("\\d+|(\\d+[.]\\d{2})");
        Matcher m_monto = p_monto.matcher(monto);
        
        try
        {
            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
            conn = DriverManager.getConnection (url, userName, password);
            System.out.println ("Database connection established");
            s = conn.createStatement ();

            s.executeQuery ("SELECT * FROM usuario WHERE dpi=\""+dpi+"\" AND estado!=\"Prestamo\"");
            rs = s.getResultSet ();
            if (!m_monto.matches())
            {
                error = "<p style=\"color:red\">(*) Error: El monto debe ser numerico en formato #### o ####.##</p>";
                actual.setAttribute("error_correo", error);
                response.sendRedirect("prestamos.jsp");
            }
            else if (rs.next())
            {
                String query = "UPDATE `bancofarmville`.`usuario` SET `estado`='Prestamo', `monto`=`monto`+"+monto;
                query = query + " WHERE `DPI`=\""+dpi+"\"";
                s.execute(query);
                
                AddTransaccion addt = new AddTransaccion("Prestamo","-",monto,dpi,s,"6");
                actual.setAttribute("error_correo", "<p style=\"color:green\">(*) El prestamo por $"+monto+" ha sido realizado</p>");
                response.sendRedirect("prestamos.jsp");
                
            }
            else
            {
                actual.setAttribute("error_correo", "<p style=\"color:red\">(*) Error: Su usuario actualmente tiene un prestamo pendiente</p>");
                response.sendRedirect("prestamos.jsp");
            }
           
        }
        catch (Exception e)
        {
           System.err.println ("No se pudo conectar a la base de datos " + e.getMessage());
        }
        finally
        {
           if (conn != null)
           {
               try
               {
                   conn.close ();
                   System.out.println ("Conexión Finalizada");
               }
               catch (Exception e) {  }
           }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
